package com.jxpanda.infrastructure.spring.toolkit;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.ResolvableType;

/**
 * @author Panda
 */
@Slf4j
public class SpringContextKit {

    private static ApplicationContext applicationContext;

    public static void init(ApplicationContext applicationContext) {
        if (applicationContext != null) {
            log.info("[SpringContextKit] SpringContextKit 初始化完成");
            SpringContextKit.applicationContext = applicationContext;
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBean(ResolvableType resolvableType) {
        String[] beanNames = applicationContext.getBeanNamesForType(resolvableType);
        if (beanNames.length > 0) {
            return getBean(beanNames[0]);
        }
        return null;
    }

    public static <T> T getBeanOrDefault(ResolvableType resolvableType, T defaultBean) {
        T bean = getBean(resolvableType);
        return (bean != null) ? bean : defaultBean;
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static <T> T getBeanOrNull(Class<T> clazz) {
        try {
            return applicationContext.getBean(clazz);
        } catch (NoSuchBeanDefinitionException ex) {
            return null;
        }
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }

    public static <T> T getBeanOrDefault(Class<T> clazz, T defaultBean) {
        T bean = getBeanOrNull(clazz);
        if (bean == null) {
            log.info("[SpringContextKit] bean {} not found, use default bean {}", clazz.getName(), defaultBean.getClass().getName());
            return defaultBean;
        }
        return bean;
    }


}
